# Define forwarding parameters (modify as needed)
$windowsPort = 8000       # Windows listening port
$wslPort = 80             # WSL2 target port
$ruleName = "WSL2-Port-Forward-$windowsPort"  # Firewall rule name

# Get WSL2 IP address
try {
    $wslIp = wsl -- hostname -I | ForEach-Object { $_.Split(' ')[0] }
    
    if (-not $wslIp -or $wslIp -eq "") {
        throw "Failed to get WSL2 IP address. Please ensure WSL2 is running."
    }

    Write-Host "Detected WSL2 IP: $wslIp" -ForegroundColor Green
}
catch {
    Write-Host "Error: $_" -ForegroundColor Red
    exit 1
}

# Delete old forwarding rule (if exists)
try {
    Write-Host "Removing old forwarding rule..." -ForegroundColor Cyan
    netsh interface portproxy delete v4tov4 listenport=$windowsPort listenaddress=0.0.0.0 2>&1 | Out-Null
}
catch {
    # Ignore "rule not found" errors
}

# Add new forwarding rule
try {
    Write-Host "Configuring new forwarding rule: Windows $windowsPort -> WSL2 $wslIp`:$wslPort" -ForegroundColor Cyan
    netsh interface portproxy add v4tov4 `
        listenport=$windowsPort `
        listenaddress=0.0.0.0 `
        connectport=$wslPort `
        connectaddress=$wslIp

    # Verify rule creation
    $rules = netsh interface portproxy show all | FindStr $windowsPort
    if (-not $rules) {
        throw "Forwarding rule not created. Please check permissions."
    }
}
catch {
    Write-Host "Failed to configure forwarding rule: $_" -ForegroundColor Red
    exit 1
}

# Configure firewall inbound rule
try {
    Write-Host "Configuring firewall inbound rule..." -ForegroundColor Cyan
    
    # Remove old rule with same name if exists
    Remove-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue
    
    # Create new firewall rule
    New-NetFirewallRule `
        -DisplayName $ruleName `
        -Direction Inbound `
        -LocalPort $windowsPort `
        -Protocol TCP `
        -Action Allow `
        -Profile Any  # Allows all network profiles (modify to Private if needed)

    # Verify firewall rule
    $firewallRule = Get-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue
    if ($firewallRule) {
        Write-Host "Firewall inbound rule configured successfully (allows TCP $windowsPort)" -ForegroundColor Green
    }
    else {
        throw "Firewall rule creation failed"
    }
}
catch {
    Write-Host "Failed to configure firewall: $_" -ForegroundColor Red
    exit 1
}

# Final message
Write-Host "`n✅ All configurations completed!" -ForegroundColor Green
Write-Host "You can access WSL2's port $wslPort via http://localhost:$windowsPort" -ForegroundColor Yellow